#!/bin/bash
# Installs a downloaded KUARIO Print update as root. The app runs it through pkexec
# (src/modules/update/linux-updater.js), so polkit shows the action com.kuario.print.update from
# com.kuario.print.policy with our message. electron-updater itself runs `pkexec /bin/bash -c ...`,
# which polkit shows as a bare command line (AGENTS.md, Linux auto-update).
#
# Usage: pkexec "/opt/KUARIO Print/resources/kuario-update" <file.rpm|file.deb>
#
# The checks below are a safety net, not a security boundary: polkit has already asked for an
# administrator (auth_admin). Never relax that action to "yes", or any local process could install
# any package as root.

set -u

fail() {
	echo "kuario-update: $*" >&2
	exit 1
}

[ "$(id -u)" -eq 0 ] || fail "must run as root, through pkexec"
[ $# -eq 1 ] || fail "usage: kuario-update <file.rpm|file.deb>"

file=$1
case "$file" in
/*) ;;
*) fail "not an absolute path: $file" ;;
esac
[ -f "$file" ] && [ ! -L "$file" ] || fail "not a regular file: $file"

# only a file of the user who asked; pkexec sets PKEXEC_UID
if [ -n "${PKEXEC_UID:-}" ]; then
	[ "$(stat -c %u "$file")" = "$PKEXEC_UID" ] || fail "not owned by the calling user: $file"
fi

case "$file" in
*.rpm)
	name=$(rpm -qp --qf '%{NAME}' "$file" 2>/dev/null) || fail "not an rpm: $file"
	[ "$name" = "kuario-print" ] || fail "not a kuario-print package: $name"
	# same package managers and options as electron-updater 6.3.9 (RpmUpdater.doInstall)
	if command -v zypper >/dev/null 2>&1; then
		exec zypper --no-refresh install --allow-unsigned-rpm -y -f "$file"
	elif command -v dnf >/dev/null 2>&1; then
		exec dnf -y install "$file"
	else
		exec yum -y install "$file"
	fi
	;;
*.deb)
	name=$(dpkg-deb -f "$file" Package 2>/dev/null) || fail "not a deb: $file"
	[ "$name" = "kuario-print" ] || fail "not a kuario-print package: $name"
	# same as electron-updater 6.3.9 (DebUpdater.doInstall)
	dpkg -i "$file" || apt-get install -f -y
	;;
*)
	fail "not an rpm or deb: $file"
	;;
esac
